<?php
namespace frontend\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\Response;
use yii\base\ErrorException;
use yii\helpers\Html;
use common\models\member\Member;
use common\models\oauthsinawb\Oauthsinawb;
use yii\web\UploadedFile;
use zhongkefu\zhongkefu;
use zhongkefu\helpers\sinaweiboclass;
use frontend\models\FenhuiForm;
use common\models\Setting\Setting;
use common\models\adminlog\AdminLog;

/**
 *  新浪微博授权回调
 * 
 * @author        dwheng
 */
class SinawbCallBackController extends Controller {

    public function actionIndex() {        
		$config = Setting::findBySql('SELECT value FROM setting where code="wb_akey" or code="wb_skey" or code="wb_callback"')->asArray()->all();	
	    $sinawb = new Sinaweiboclass( $config[0]['value'] , $config[1]['value'] );
		
		if (isset($_REQUEST['code'])) {
			$keys = array();
			$keys['code'] = $_REQUEST['code'];
			$keys['redirect_uri'] = $config[0]['value'];
			$token = $sinawb->getAccessToken( 'code', $keys ) ;
			if($token) {
				echo "<script>alert('登录失败！');window.location.href='/auth/signup';</script>";
			}
		}
		if ($token) {
            Yii::$app->session['access_token'] = $access_token = $token['access_token'];
			$openid = $token['uid'];
			
            //设置cookie
/* 			$cookie_name = 'weibojs_'.$openid;
			$cookie = new CHttpCookie($cookie_name, http_build_query($token));
			$cookie->expire = time()+60*60*24*30;  //有限期30天
			Yii::app()->request->cookies[$cookie_name]=$cookie; */
            
			//获取用户信息
			$c = new SaeTClientV2( $config[0]['value'] , $config[1]['value'] , $access_token );
			$user_info = $c->show_user_by_id( $openid);//根据ID获取用户等基本信息
			if(isset($user_info['error']) && $user_info['error']){
				echo "<script>alert('登录失败！');window.location.href='/auth/signup';</script>";
			}
			
			//查看是否已绑定
			$bind = Oauthsinawb::model()->findByPk($openid);

			//数据
			$data = array(
                'type'          => 'sinawb', 
                'access_token'  => $access_token, 
                'openid'        => $openid,
                'uid'           => $bind ? $bind->uid : 0,
                'username'      => $user_info['screen_name'],
                'avatar'        => $user_info['avatar_large']
            );
		    
			//绑定注册
			$this->bind_register($bind, $data);

		}else{
			echo "<script>alert('登录失败！');window.location.href='/auth/signup';</script>";
		}
    }
	/**
	 * 绑定注册
     * 
	 * @param $bind 是否已经绑定
	 * @param $data 接收的第三方用户数据
	 */
	public function bind_register($bind, $data=array())
    {
		if(!$data['username']){
			echo "<script>alert('登录失败！');window.location.href='/auth/signup';</script>";
		}
		//初始密码
        $initPwd = substr(md5($data['username'].'_'.$data['type']), 0, 8);
		if(!$bind){
			
			//生成本地用户名
			$username = $data['username'].'_'.$data['type'];
          
			$model = new Oauthsinawb();
			$model->uid = 0; 
			$model->openid = $data['openid'];
			$model->access_token = $data['access_token'];

			//判断用户名是否已经存在
			$if_exist = Member::model()->find('username=:username', array(':username'=>$username));
			if(!$if_exist){
				//注册本地账号
				$adlog = new AdminLog();
				$user_model = new Member();
				$user_model->username = $username; //分配用户名
				$user_model->setPassword($password);
				$user_model->generateAuthKey();			
				//$user_model->avatar = $data['avatar'];     //调用空间头像(100*100)	
				$user_model->status = 10;
				$user_model->ip = $adlog->real_ip();  //注册ip
				if($user_model->save()){
					$model->uid = $uid = $user_model->uid;					
					//保存第三方授权信息
					$model->save();
					
					//保存远程图片到本地
					/*$avatar_name = 'small_'.$user_model->uid.'_'.substr(md5(uniqid('file')), 0,11);
					$filepath = 'upload/avatar/'.date('Ym',time());
					$remote = Helper::downloadImage($data['avatar'], ROOT_PATH.'/'.$filepath, $avatar_name);
					if($remote){
						$local_avatar = $filepath.'/'.$remote['filename'];
						$bind_user = User::model()->findByPk($uid);
						$bind_user->avatar = $local_avatar;
						$bind_user->save();
					}*/
					
				}else{
					echo "<script>alert('登录失败！');window.location.href='/auth/signup';</script>";
				}	
			}else{
				$uid = $if_exist->id;
				$model->uid = $uid;
				//保存绑定qq用户
				$model->save();
			}			
						
		}else{
			//已经绑定
			$uid = $data['uid'];
		}
		$user = Member::model()->findByPk($uid);
		$username = $user->username;
		
		//自动登录
		if (Yii::$app->getUser()->login($user)) {
            return $this->redirect(['/member/info']);
        }else{
			echo "<script>alert('登录失败！');window.location.href='/auth/signup';</script>";
		}
	}
}
